package com.bdth.bdthiss.plus;

import com.bdth.bdthiss.jsoup.FileTools;
import com.bdth.bdthiss.jsoup.JdImgTools;
import com.bdth.bdthiss.util.MD5Utils;
import com.google.common.collect.Lists;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.os.WindowsUtils;

import java.io.*;
import java.util.*;

/**
 * Created by Administrator on 2020/5/11.
 */
public class TmallPage {
    private static String fristUrl = "https://chenguang.tmall.com/search.htm?spm=a1z10.3-b-s.w4011-14939493465.407.2d0d3a16BJG2aE&search=y&scene=taobao_shop&pageNo=1&tsearch=y#anchor";
    public static List<Integer> back_tracks = new ArrayList<>();
    private static String chromePath = "C:/Users/Think/AppData/Local/Google/Chrome/Application/";
    private static int DEFAULT_TIMEOUT = 15;
    private static String loginUrl = "https://login.tmall.com/";
    private static String username = "13285202553";
    private static String password = "bdth1234";

    /**
     * 根据url下载商品图片
     * @param uid 商品编码
     * @param url 商品网络地址
     * @param saveWhere 保存的位置
     * @return
     * 例如 url = http://www.officemate.cn/product-391327.html
     *      uid = 391327
     *      saveWhere = "C:\\jsoup\\images\\"
     */
    public static Map<String,String> getHtmlAndDownPic(String uid, String url, String saveWhere) throws Exception{
        Map<String, String> result = new HashMap<>();
        String html = "";
        try {
            WebDriver driver = login();
            driver.get(url);
            driver.navigate().refresh();
            Thread.sleep(3000);
            html = driver.getPageSource();
            driver.quit();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        //获取url的文档
        Document document = Jsoup.parse(html);
        Elements div = document.select("div[class='pagination']");
        System.out.println(html.toString());
        Document divDoc = Jsoup.parse(div.toString());
        Elements thumbnails = divDoc.select("a[class='J_SearchAsync']");
        for(Element thumbnail : thumbnails){
            String src = thumbnail.attr("href");
            System.out.println(src);
        }

        return result;
    }

    public static Map<String,String> getHtmlAndDownPic(String url) throws Exception{
        Map<String, String> result = new HashMap<>();
        Cookies.addCookies();
        String html = "";
        try {
            WindowsUtils.getProgramFilesPath();
            WebDriver driver=DriverFactory.create();
            File file=new File("broswer.data");
            FileReader fr=new FileReader(file);
            BufferedReader br=new BufferedReader(fr);
            String line;
            while((line=br.readLine())!= null)
            {
                StringTokenizer str=new StringTokenizer(line,";");
                while(str.hasMoreTokens())
                {
                    String name=str.nextToken();
                    String value=str.nextToken();
                    String domain=str.nextToken();
                    String path=str.nextToken();
                    System.out.println(name);
                    System.out.println(value);
                    System.out.println(domain);
                    System.out.println(path);
                    Date expiry=null;
                    String dt;
                    if(!(dt=str.nextToken()).equals(null))
                    {
                        //expiry=new Date(dt);
                        System.out.println();
                    }
                    boolean isSecure=new Boolean(str.nextToken()).booleanValue();
                    Cookie ck=new Cookie(name,value,domain,path,expiry,isSecure);
                    driver.manage().addCookie(ck);
                }
            }
            driver.get(url);
            html = driver.getPageSource();
            Document document = Jsoup.parse(html);
            Elements div = document.select("span[class='sn-welcome-info']");
            System.out.println(div.text());
            if(div==null||div.text().equals("")){
                Cookies.addCookies();
                getHtmlAndDownPic(url);
            }
            driver.navigate().refresh();
            Thread.sleep(3000);
            html = driver.getPageSource();
            driver.quit();
        }catch (Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        //获取url的文档
        Document document = Jsoup.parse(html);
        Elements div = document.select("div[class='pagination']");
        System.out.println(html.toString());
        Document divDoc = Jsoup.parse(div.toString());
        Elements thumbnails = divDoc.select("a[class='J_SearchAsync']");
        for(Element thumbnail : thumbnails){
            String src = thumbnail.attr("href");
            System.out.println(src);
        }

        return result;
    }

    public static WebDriver login(){
        WebDriver driver = null;
        try {
            System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
            ChromeOptions chromeOptions = new ChromeOptions();
            //chromeOptions.addArguments("--headless");
            driver = new ChromeDriver(chromeOptions);
            driver.get(loginUrl);

            //模拟点击到账号密码登陆
            driver.findElement(By.id("fm-login-password")).click();
            Thread.sleep(1000);
            driver.manage().window().maximize();
            //driver.findElement(By.id("J_Quick2Static")).click();
            driver.findElement(By.id("fm-login-id")).sendKeys(username);
            Thread.sleep(1000);
            driver.findElement(By.id("fm-login-password")).sendKeys(password);
            Thread.sleep(1000);
            WebElement nc_1_n1z = driver.findElement(By.id("nc_1_n1z"));
            Actions actions = new Actions(driver);
            actions.clickAndHold(nc_1_n1z);
            Random ra =new Random();
//            for (Double tack : tacks) {
//                int a = tack.intValue();
//                int yoffset_random = ra.nextInt(6) - 2;
//                actions.moveByOffset(slider,500,0).perform();
//                //Thread.sleep(20+ ra.nextInt(20));
//            }
            actions.dragAndDropBy(nc_1_n1z,500,0);
            Thread.sleep(200+ ra.nextInt(400));

            for (Integer back_track : back_tracks) {
                int yoffset_random = ra.nextInt(4) - 2;
                actions.moveByOffset(back_track, yoffset_random).perform();
            }


            int x = ra.nextInt(3) - 4;
            int y = ra.nextInt(4) - 2;
            actions.moveByOffset(x, y).perform();
            x = ra.nextInt(2) +1;
            y = ra.nextInt(4) - 2;
            actions.moveByOffset(x, y).perform();
            Thread.sleep(200+ ra.nextInt(400));
            driver.findElement(By.className("password-login")).click();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return driver;
    }
    /**
     * 测试方法
     * @param args
     */
    public static void main(String[] args) {
        try {
            TmallPage.getHtmlAndDownPic(fristUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
